package small.woods.msRedis.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import small.woods.msRedis.service.impl.RedisLockServiceImpl;

import java.util.UUID;

/**
 * @description: 分布式锁---redis实现工具类操作
 * @author: yutingting
 * @create: 2022-01-18 20:27
 **/
@Service
@Slf4j
public class RedisLockUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 进行加锁操作
     * @param key
     * @return
     */
    public boolean getLock(String key){
        return redisTemplate.opsForValue().setIfAbsent(key, UUID.randomUUID().toString());
    }

    /**
     * 释放锁操作
     * @param key
     */
    public void unLock(String key){
        redisTemplate.delete(key);
        System.out.println(String.format("%s释放了redis锁%s", RedisLockServiceImpl.remark,redisTemplate));
    }

    /**
     * 通过key获取value值
     * @param key
     * @return
     */
    public String getValue(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 进行赋值操作
     * @param key
     * @param value
     */
    public void setValue(String key, String value){
        redisTemplate.opsForValue().set(key, value);
    }
}
